//IsOwner 
// 主机
using JKFrame;
using Unity.Netcode;
using UnityEngine;

public partial class Player : NetworkBehaviour, IStateMachineOwner
{
    #region 内部类型
    public class InputData
    {
        public Vector3 moveDir;
    }
    #endregion

    #region 面板赋值
    [SerializeField] private float moveSpeed = 1;
    public float MoveSpeed { get => moveSpeed; }
    [SerializeField] private float rotateSpeed = 1000;
    public float RotateSpeed { get => rotateSpeed; }
    [SerializeField] private CharacterController characterController;
    public CharacterController CharacterController { get => characterController; }
    [SerializeField] private PlayerView view;
    public PlayerView View { get => view; }
    [SerializeField] private Animator animator;
    public Animator Animator { get => animator; }


    #endregion

    public Vector2Int currentAOICoord { get; private set; }
    public InputData inputData { get; private set; }
    private StateMachine stateMachine;
    private void Server_OnNetworkSpawn()
    {
        stateMachine = new StateMachine();
        stateMachine.Init(this);
        inputData = new InputData();
        currentAOICoord = AOIUtility.GetCoordByWorldPostion(transform.position);
        AOIUtility.AddPlayer(this, currentAOICoord);
        ChangeState(PlayerState.Idle);
    }

    private void Server_ReceiveMoveInput(Vector3 moveDir)
    {
        inputData.moveDir = moveDir.normalized;
        // 状态类中根据输入情况进行运算
    }

    private void Server_OnNetworkDespawn()
    {
        stateMachine.Destroy();
        AOIUtility.RemovePlayer(this, currentAOICoord);
    }

    public void ChangeState(PlayerState newState)
    {
        currentState.Value = newState;
        switch (newState)
        {
            case PlayerState.Idle:
                stateMachine.ChangeState<PlayerIdleState>();
                break;
            case PlayerState.Move:
                stateMachine.ChangeState<PlayerMoveState>();
                break;
        }
    }

    public void PlayAnimation(string animationName, float fixedTransitionDuration = 0.25f)
    {
        animator.CrossFadeInFixedTime(animationName, fixedTransitionDuration);
    }

    public void UpdateAOICoord()
    {
        Vector2Int newCoord = AOIUtility.GetCoordByWorldPostion(transform.position);
        if (newCoord != currentAOICoord) // 发生了地图块坐标变化
        {
            AOIUtility.UpdatePlayerCoord(this, currentAOICoord, newCoord);
            currentAOICoord = newCoord;
        }
    }

}

